<script setup>
import {Message} from '@arco-design/web-vue'
import {computed, ref, watch} from 'vue'
import {route} from "ziggy-js";

const props = defineProps({
    // 文件大小限制（MB）
    maxSize: {
        type: Number,
        default: 5
    },
    // 支持的图片类型
    accept: {
        type: String,
        default: 'image/jpeg,image/png,image/gif,image/webp'
    },
    // 提示文本
    tip: {
        type: String,
        default: ''
    },
    // 是否显示上传进度
    showProgress: {
        type: Boolean,
        default: true
    },
    // 是否允许拖拽上传
    draggable: {
        type: Boolean,
        default: true
    }
})

const modelValue = defineModel('modelValue', { type: String, default: '' })

const action = route('admin.upload.image')
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
const headers = {
    'X-CSRF-TOKEN': csrfToken,
}

// 响应式状态
const uploadProgress = ref(0)
const isUploading = ref(false)
const isDragOver = ref(false)
const errorMessage = ref('')
const fileList = ref([])

// 计算属性
const hasImage = computed(() => !!modelValue.value)
const progressPercentage = computed(() => Math.round(uploadProgress.value * 100))

// 监听modelValue变化，同步到fileList
watch(modelValue, (newVal) => {
    if (newVal && !fileList.value.some(file => file.url === newVal)) {
        fileList.value = [{
            uid: '-1',
            name: '已上传图片',
            url: newVal,
            status: 'done'
        }]
    }
}, { immediate: true })

// 事件处理
const handleSuccess = (currentFile) => {
    if (currentFile.response.code === 200) {
        modelValue.value = currentFile.response.data.url
        Message.success('图片上传成功')
        errorMessage.value = ''
    } else {
        Message.error('图片上传失败')
        errorMessage.value = '上传失败，请重试'
    }
    isUploading.value = false
    uploadProgress.value = 0
}

const handleError = (fileItem) => {
    Message.error('图片上传失败')
    errorMessage.value = fileItem.response?.message || '上传失败，请重试'
    isUploading.value = false
    uploadProgress.value = 0
}

const handleProgress = (event) => {
    uploadProgress.value = event.percent
}

const handleBeforeUpload = (file) => {
    // 重置状态
    errorMessage.value = ''
    isUploading.value = true

    // 文件类型验证
    const validTypes = props.accept.split(',')
    if (!validTypes.includes(file.type)) {
        Message.error(`不支持的文件格式，请上传 ${props.accept.replace(/image\//g, '').split(',').join('、')} 格式的图片`)
        isUploading.value = false
        return false
    }

    // 文件大小验证
    const maxSizeInBytes = props.maxSize * 1024 * 1024
    if (file.size > maxSizeInBytes) {
        Message.error(`文件大小不能超过 ${props.maxSize}MB`)
        isUploading.value = false
        return false
    }

    return true
}

const handleRemove = () => {
    modelValue.value = ''
    fileList.value = []
    Message.info('已移除图片')
}

const handleDragOver = (e) => {
    if (!props.draggable) return
    e.preventDefault()
    isDragOver.value = true
}

const handleDragLeave = () => {
    isDragOver.value = false
}

const handleDrop = (e) => {
    if (!props.draggable) return
    e.preventDefault()
    isDragOver.value = false
}
</script>

<template>
    <div class="image-upload-container">
        <a-upload
            :action="action"
            :before-upload="handleBeforeUpload"
            :disabled="isUploading"
            :draggable="draggable"
            :file-list="fileList"
            :headers="headers"
            :show-file-list="false"
            :with-credentials="true"
            accept="image/*"
            name="file"
            @drop="handleDrop"
            @error="handleError"
            @progress="handleProgress"
            @success="handleSuccess"
            @drag-over="handleDragOver"
            @drag-leave="handleDragLeave"
        >
            <template #upload-button>
                <div
                    :class="{
            'has-image': hasImage,
            'is-uploading': isUploading,
            'is-drag-over': isDragOver,
            'has-error': errorMessage
          }"
                    class="upload-area"
                >
                    <!-- 上传中状态 -->
                    <div v-if="isUploading" class="upload-status uploading">
                        <div class="progress-container">
                            <a-progress
                                :percent="progressPercentage"
                                :stroke-width="4"
                                class="upload-progress"
                                size="mini"
                                type="circle"
                            />
                            <div class="upload-text">上传中... {{ progressPercentage }}%</div>
                        </div>
                    </div>

                    <!-- 已上传图片状态 -->
                    <div v-else-if="hasImage" class="upload-status has-image">
                        <div class="image-preview">
                            <img :src="modelValue" alt="预览图片" class="preview-image" />
                            <div class="image-overlay">
                                <div class="action-buttons">
                                    <a-tooltip content="更换图片">
                                        <a-button class="action-btn" size="mini" type="outline">
                                            <icon-edit />
                                        </a-button>
                                    </a-tooltip>
                                    <a-tooltip content="删除图片">
                                        <a-button
                                            class="action-btn"
                                            size="mini"
                                            status="danger"
                                            type="outline"
                                            @click.stop="handleRemove"
                                        >
                                            <icon-delete />
                                        </a-button>
                                    </a-tooltip>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 默认上传状态 -->
                    <div v-else class="upload-status default">
                        <div class="upload-placeholder">
                            <div class="upload-icon">
                                <icon-plus />
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </a-upload>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
            <icon-exclamation-circle-fill class="error-icon" />
            <span>{{ errorMessage }}</span>
        </div>

        <!-- 自定义提示 -->
        <div v-if="tip" class="custom-tip">
            {{ tip }}
        </div>
    </div>
</template>

<style lang="scss" scoped>
.image-upload-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.upload-area {
    position: relative;
    width: 120px;
    height: 120px;
    border: 2px dashed var(--color-border-3);
    border-radius: 8px;
    background: var(--color-fill-2);
    transition: all 0.3s ease;
    cursor: pointer;
    overflow: hidden;
}

.upload-area:hover {
    border-color: var(--color-primary-light-3);
    background: var(--color-fill-1);
}

.upload-area.is-drag-over {
    border-color: var(--color-primary);
    background: var(--color-primary-light-5);
}

.upload-area.has-error {
    border-color: var(--color-danger);
}

.upload-status {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 上传中状态 */
.uploading .progress-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
}

.upload-progress {
    :deep(.arco-progress-circle-text) {
        font-size: 14px;
        font-weight: 500;
    }
}

/* 已上传图片状态 */
.has-image .image-preview {
    position: relative;
    width: 100%;
    height: 100%;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.has-image:hover .image-overlay {
    opacity: 1;
}

.action-buttons {
    display: flex;
    gap: 8px;
}

.action-btn {
    border: none;
    color: #fff;
    backdrop-filter: blur(4px);
}

/* 默认上传状态 */
.default .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    padding: 20px;
    text-align: center;
}

.upload-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: var(--color-primary-light-5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--color-primary);
    font-size: 20px;
}

.upload-title {
    font-weight: 500;
    color: var(--color-text-1);
    margin-bottom: 4px;
}

.upload-tip {
    font-size: 12px;
    color: var(--color-text-3);
    line-height: 1.4;
}

/* 错误提示 */
.error-message {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: var(--color-danger);
    padding: 4px 8px;
    background: var(--color-danger-light-1);
    border-radius: 4px;
}

.error-icon {
    font-size: 14px;
}

/* 自定义提示 */
.custom-tip {
    font-size: 12px;
    color: var(--color-text-3);
    line-height: 1.4;
    padding: 0 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .upload-area {
        height: 140px;
    }

    .default .upload-placeholder {
        gap: 8px;
        padding: 16px;
    }

    .upload-icon {
        width: 40px;
        height: 40px;
        font-size: 18px;
    }

    .upload-title {
        font-size: 14px;
    }

    .upload-tip {
        font-size: 11px;
    }
}
</style>
